package com.google.memoryofaplace.controller;

import java.io.IOException;
import java.net.URL;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.urlfetch.HTTPHeader;
import com.google.appengine.api.urlfetch.HTTPMethod;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;

public class AuthHandler extends HttpServlet {
	private static final long serialVersionUID = 8410724390309880878L;

	public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws IOException {
		// redirect to post
		doPost(req, res);
	}

	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws IOException {
		try {
			String DEVELOPER_KEY = "AI39si5PysUYhK2EgQGh0859A8C8IzW-kUaL6tPRuGLMJOE-BoXwx-5CQiFcKDLew2NMAlYQSlfHCqewCAKvZLYXXSniCS8OiQ";
			if ((req.getParameter("action") != null)
					&& (req.getParameter("token") != null)) {
				String strAction = req.getParameter("action");
				String strUrl = "";
				if (strAction.equals("chToken"))
					strUrl = "https://www.google.com/accounts/AuthSubSessionToken";
				if (strAction.equals("getVideos"))
				{
					res.setCharacterEncoding("UTF-8");
					res.setContentType("application/json;charset=UTF-8");
					strUrl = "http://gdata.youtube.com/feeds/api/users/default/uploads/?alt=json&key="
							+ DEVELOPER_KEY;
				}
				if (strAction.equals("getPhotos"))
					strUrl = "http://picasaweb.google.com/data/feed/api/user/default/?kind=photo&access=public&alt=json";
				if (strAction.equals("debug"))
					strUrl = "http://gdata.youtube.com/feeds/users/pedregal76/uploads?alt=json&key="
							+ DEVELOPER_KEY;

				URLFetchService url = URLFetchServiceFactory
						.getURLFetchService();
				HTTPRequest httpRequest = new HTTPRequest(new URL(strUrl),
						HTTPMethod.GET);
				if (!strAction.equals("debug"))
					httpRequest.addHeader(new HTTPHeader("Authorization",
							"AuthSub token=\"" + req.getParameter("token")
									+ "\""));
				httpRequest.addHeader(new HTTPHeader("X-GData-Key",
						"X-GData-Key key=\"" + DEVELOPER_KEY + "\""));

				byte[] contenido = url.fetch(httpRequest).getContent();
				String responseString = new String(contenido);
				res.getWriter().write(responseString);
			}
		} catch (Exception e) {
			res.getWriter().write("");
		}
	}
}
